const finance = require('../../../utils/finance')
const { formatyyyyMMdd } = require('../../../utils/date')
const app = getApp()

Page({
  data: {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    days: [],
    selectedDate: '',
    recordList: [],
    recordDates: [], // 有记账记录的日期列表
    loading: false,
    // 账户相关
    accountList: [],
    accountIndex: 0,
    showAccountSelector: false,
    // 当天是否可以记账
    currentCanWrite: false
  },

  async onLoad() {
    // 设置当前系统日期为默认选中日期
    const today = new Date()
    const todayStr = formatyyyyMMdd(today)
    this.setData({ selectedDate: todayStr })
    await this.initAccount()
  },

  async onShow() {
    // 加载该日期的记账记录
    await this.initAccount()
  },

  onPullDownRefresh() {
    this.loadMonthRecords().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 初始化账户
  async initAccount() {
    const { accountList, accountIndex } = await app.getAccountGlobal()
    this.setData({ accountList, accountIndex })

    this.initCalendar()
    await this.loadMonthRecords()
    
    // 加载当前日期的记账记录
    if (this.data.selectedDate) {
      this.loadDayRecords(this.data.selectedDate)
    }
  },

  // 初始化日历
  initCalendar() {
    const { year, month } = this.data
    const days = this.generateDays(year, month)
    this.setData({ days })
  },

  // 生成日历数据
  generateDays(year, month) {
    const days = []
    const firstDay = new Date(year, month - 1, 1)
    const lastDay = new Date(year, month, 0)
    const startDate = new Date(firstDay)
    startDate.setDate(startDate.getDate() - firstDay.getDay())

    const today = new Date()
    const isCurrentMonth = year === today.getFullYear() && month === today.getMonth() + 1

    for (let i = 0; i < 42; i++) {
      const currentDate = new Date(startDate)
      currentDate.setDate(startDate.getDate() + i)
      
      const day = currentDate.getDate()
      const isCurrentMonthDay = currentDate.getMonth() === month - 1
      const isToday = isCurrentMonthDay && day === today.getDate() && isCurrentMonth
      
      const dateStr = formatyyyyMMdd(currentDate)
      const hasRecord = this.data.recordDates.includes(dateStr)
      const isSelected = dateStr === this.data.selectedDate

      days.push({
        day: day,
        date: dateStr,
        disabled: !isCurrentMonthDay,
        isToday: isToday,
        hasRecord: hasRecord,
        isSelected: isSelected
      })
    }

    return days
  },

  // 加载当月记账记录
  async loadMonthRecords() {
    if (this.data.loading) return

    this.setData({ loading: true })
    
    try {
      const { year, month } = this.data
      const monthStr = String(month).padStart(2, '0')
      const dateParam = `${year}-${monthStr}`
      
      // 获取当前选中的账户
      const account = this.data.accountList[this.data.accountIndex]
      if (!account) {
        this.setData({ loading: false })
        return
      }
      // 先去掉days的数据的选中的状态，避免数据混乱 
      this.setData({ days: this.data.days.map(item => ({ ...item, isSelected: false, hasRecord: false })) })
      const res = await finance.searchCalendarInit({ 
        yearMonth: dateParam,
        accountBookId: account.id
      })

      if (res.list && Array.isArray(res.list)) {
        const recordDates = res.list.map(item => item.financeDate)
        this.setData({ recordDates })
        
        // 重新生成日历数据以更新标记
        const days = this.generateDays(year, month)
        this.setData({ days })
      }
    } catch (error) {
      console.error('加载月度记录失败:', error)
      wx.showToast({ 
        title: '加载失败，请重试', 
        icon: 'none' 
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载指定日期的记账记录
  async loadDayRecords(date) {
    if (!date) return

    this.setData({ loading: true })
    
    try {
      // 获取当前选中的账户
      const account = this.data.accountList[this.data.accountIndex]
      if (!account) {
        this.setData({ loading: false })
        return
      }
      
      const res = await finance.searchCalendarDay({ 
        date,
        accountBookId: account.id
      })
      if (res && (Array.isArray(res.itemList) || Array.isArray(res))) {
        // 这里还有res是为了兼容旧版
        const recordList = (res.itemList || res || []).map(item => ({
          id: item.id || item.accountBookId, // 若无id则用accountBookId
          type: item.financeType, // 'expense' or 'income'
          category: item.categoryName,
          categoryCode: item.categoryCode,
          financeDesc: item.financeDesc || '',
          amount: item.totalAmount,
          paymentMethod: item.paymentMethod,
          financeDate: item.financeDate,
          financeTime: item.financeTime,
          details: [],
          expanded: false,
          userName: item.userName
        }));
        
        // 计算当天收入和支出总额
        let dayIncomeTotal = 0;
        let dayExpenseTotal = 0;
        
        recordList.forEach(record => {
          const amount = parseFloat(record.amount) || 0;
          if (record.type === 'income') {
            dayIncomeTotal += amount;
          } else if (record.type === 'expense') {
            dayExpenseTotal += amount;
          }
        });
        
        this.setData({ 
          recordList,
          dayIncomeTotal: dayIncomeTotal.toFixed(2),
          dayExpenseTotal: dayExpenseTotal.toFixed(2),
          currentCanWrite: res.canWrite
        })
      } else {
        this.setData({ recordList: [] })
      }
    } catch (error) {
      console.error('加载日期记录失败:', error)
      wx.showToast({ 
        title: '加载失败，请重试', 
        icon: 'none' 
      })
      this.setData({ recordList: [] })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 上个月
  onPrevMonth() {
    let { year, month } = this.data
    if (month === 1) {
      year--
      month = 12
    } else {
      month--
    }
    
    this.setData({ 
      year, 
      month,
      selectedDate: '',
      recordList: []
    })
    
    this.initCalendar()
    this.loadMonthRecords()
  },

  // 下个月
  onNextMonth() {
    let { year, month } = this.data
    if (month === 12) {
      year++
      month = 1
    } else {
      month++
    }
    
    this.setData({ 
      year, 
      month,
      selectedDate: '',
      recordList: []
    })
    
    this.initCalendar()
    this.loadMonthRecords()
  },

  // 点击日期
  onDayTap(e) {
    const { date, day } = e.currentTarget.dataset
    
    if (!date) return
    
    // 保存当前的days状态，避免hasRecord状态丢失
    const currentDays = [...this.data.days]
    
    // 更新选中状态，保持原有的hasRecord状态
    const days = currentDays.map(item => ({
      ...item,
      isSelected: item.date === date
    }))
    
    this.setData({ 
      days,
      selectedDate: date
    })
    
    // 加载该日期的记账记录
    this.loadDayRecords(date)
  },

  // 添加记账
  onAddRecord() {
    if (!this.data.selectedDate) {
      wx.showToast({ 
        title: '请先选择日期', 
        icon: 'none' 
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/finance/write/write?date=${this.data.selectedDate}`
    })
  },

  // 删除记录后刷新
  onDeleteRecord() {
    // 刷新月度记录和当前日期记录
    this.loadMonthRecords()
    if (this.data.selectedDate) {
      this.loadDayRecords(this.data.selectedDate)
    }
  },

  // 账户选择相关方法
  clickShowAccountSelector() {
    this.setData({ showAccountSelector: true })
  },

  async onSelectAccount(e) {
    const idx = e.detail.index
    // 设置全局账户索引
    app.setAccountIdxGlobal(idx)
    this.setData({ 
      accountIndex: idx,
      showAccountSelector: false,
      selectedDate: '',
      recordList: []
    })
    
    // 重新加载数据
    this.loadMonthRecords()
  }
}) 